<template>
  <div class="pager-container" v-if="pageTotal > 1">
    <a @click="handleClick(1)" :class="{ disabled: current == 1 }">|&lt;&lt;</a>
    <a @click="handleClick(current - 1)" :class="{ disabled: current == 1 }"
      >&lt;&lt;</a
    >
    <a
      @click="handleClick(n)"
      v-for="(n, i) in number"
      :key="i"
      :class="{ active: current == n }"
      >{{ n }}</a
    >
    <a
      @click="handleClick(current + 1)"
      :class="{ disabled: current == pageTotal }"
      >&gt;&gt;</a
    >
    <a
      @click="handleClick(pageTotal)"
      :class="{ disabled: current == pageTotal }"
      >&gt;&gt;|</a
    >
  </div>
</template>

<script>
export default {
  props: {
    current: {
      //当前页码
      type: Number,
      default: 1,
    },
    total: {
      //总数据量
      type: Number,
      default: 300,
    },
    limit: {
      //页容量
      type: Number,
      default: 10,
    },
    visibleNumber: {
      //可见页码数
      type: Number,
      default: 10,
    },
  },
  computed: {
    pageTotal() {
      return Math.ceil(this.total / this.limit);
    },
    min() {
      let min = this.current - this.visibleNumber / 2;
      if (min < 1) {
        min = 1;
      }
      return min;
    },
    max() {
      let max = this.current + this.visibleNumber / 2;
      if (max > this.pageTotal) {
        max = this.pageTotal;
      }
      return max;
    },
    number() {
      let arr = [];
      for (let i = this.min; i <= this.max; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
  methods: {
    handleClick(newPage) {
      //   console.log(newPage)
      if (newPage < 1) {
        newPage = 1;
      }
      if (newPage > this.pageTotal) {
        newPage = this.pageTotal;
      }
      if (newPage == this.current) {
        return;
      }
      this.$emit("pageChange", newPage);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/style/var.less";
.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  cursor: pointer;
  a {
    color: @primary;
    margin: 0px 10px;
    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }
    &.active {
      color: @words;
      font-weight: bold;
    }
  }
}
</style>